<?php

namespace App\Http\Controllers\Api;

use App\Models\Product;
use App\Models\ProductCate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductCateController extends ApiController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse
     */
    public function index()
    {
        $data = ProductCate::withDepth()->withCount('products')->get()->toTree();

        return $this->success($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function store(Request $request)
    {
        $parentId = $request->input('parent_id');
        try {
            if ($parentId) {
                $parent = ProductCate::find($parentId);
                ProductCate::create($request->except('parent_id'), $parent);
            } else {
                ProductCate::create($request->except('parent_id'));
            }

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return JsonResponse
     */
    public function show($id)
    {
        $cate = ProductCate::findOrFail($id);

        return $this->success($cate);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param  int  $id
     * @return JsonResponse
     */
    public function update(Request $request, $id)
    {
        $category = ProductCate::findOrFail($id);

        try {
            if ($request->parent_id) {
                if($request->parent_id == $id) {
                    throw new \Exception('分类不能是自己');
                }

                $other = ProductCate::find($request->parent_id);
                if($category->isAncestorOf($other)) {
                    throw new \Exception('分类不能是自己的子类');
                }
            }

            $category->update($request->all());

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return JsonResponse
     */
    public function destroy($id)
    {
        try {
            if (Product::where('cate_id', $id)->exists()) {
                throw new \Exception('该分类下存在产品，请先转移后再删除！');
            }

            if (ProductCate::where('parent_id', $id)->exists()) {
                throw new \Exception('该分类下存在子分类，请先转移后再删除！');
            }
            ProductCate::destroy($id);

            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e);
        }
    }
}
